var infowindow = new google.maps.InfoWindow();
var map;
var map_markers;
var map_marker_my_position = null;

var image_my_position = new google.maps.MarkerImage(
	TPL_PATH + 'images/map/pin-you-are-here.png',
	new google.maps.Size(40, 53),
	new google.maps.Point(0, 0),
	new google.maps.Point(0, 53)
);
//var shadow_my_position = new google.maps.MarkerImage(
//	TPL_PATH + 'images/map/centerpoint.png',
//	new google.maps.Size(22, 22),
//	new google.maps.Point(0, 0),
//	new google.maps.Point(-9, 20)
//);

(function () {
	google.maps.Map.prototype.markers = new Array();
	google.maps.Map.prototype.getMarkers = function() {
		return this.markers;
	};
	google.maps.Map.prototype.clearMarkers = function() {
		for(var i=0; i<this.markers.length; i++){
			this.markers[i].setMap(null);
		}
		this.markers = new Array();
	};
	google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;
	google.maps.Marker.prototype.setMap = function(map) {
		if (map) {
			map.markers[map.markers.length] = this;
		}
		this._setMap(map);
	};
})();

//
//google.maps.event.addDomListener(window, 'load', function() {
//	initialize();
//});

//
//$(document).ready(function(){
//	$('#main-container').css('background-position', 'left 85px');
//	$('#ddlMapCountry').sSelect({ddMaxHeight: '300px'});
//	//
//	$('#btnMapSearch').click(function() {
//		searchAddress();
//	});
//
//	loadRegions($('#ddlMapCountry').val());
//});

//
function initializeGoogleMaps(x, y, zoom, id) {
	//
	var point = new google.maps.LatLng(x, y);
	
	//
	var myOptions = {
		zoom: zoom,
		center: point,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	//
	map = new google.maps.Map(document.getElementById(id), myOptions);
	
	//
	google.maps.event.addListener(map, 'click', function() {
		infowindow.close();
	});
	
	//
	//searchAddress();
}

//
function showMyCurrentPosition() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {
			point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			if (map_marker_my_position === null) {
				map_marker_my_position = new google.maps.Marker({ 
					position: point, 
					map: map, 
					icon: image_my_position, 
					//shadow: shadow_my_position, 
					title: 'Вы здесь'
				});
			}
			var latlngbounds = new google.maps.LatLngBounds(point);
			map.setCenter(latlngbounds.getCenter());
			map.setZoom(16);
		});
	}
}

//
function resizeMap() {
	google.maps.event.trigger(map, 'resize');
}

//
function searchAddress() {
	var geocoder = new google.maps.Geocoder();
	var country = parseInt($('#ddlMapCountry').val()) > 0 ? $('#ddlMapCountry :selected').text() : '';
	var region = parseInt($('#ddlMapRegion').val()) > 0 ? $('#ddlMapRegion :selected').text() : '';
	var city = parseInt($('#ddlMapCity').val()) > 0 ? $('#ddlMapCity :selected').text() : '';
	//var street = $('#txtMapStreet').val();
	//if (street == 'Улица:' || trim(street) == '')
	//{
	//	street = '';
	//}

	var address = trim(country + ' ' + region + ' ' + city);
	var zoom = 5;

	if (city != '') {
		zoom = 11;
	}
	else if (region != '') {
		zoom = 8
	}
	else if (country != '') {
		zoom = 5;
	}

	if (geocoder) {
		geocoder.geocode({ 'address': address }, function (results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				//alert(results[0].geometry.location);
				//var mapY = results[0].geometry.location.lat();
				//var mapX = results[0].geometry.location.lng();
				var image = new google.maps.MarkerImage(
					TPL_PATH + 'images/map_pointer.png',
					new google.maps.Size(20, 22),
					new google.maps.Point(0, 0),
					new google.maps.Point(0, 22)
				);
				map.setCenter(results[0].geometry.location);
				map.setZoom(zoom);
				//marker.setIcon(image);
				//marker.setPosition(results[0].geometry.location);
				//google.maps.event.addListener(marker, 'click', onMarkerClick);

				$.ajax({
					url: SITE_ROOT + 'ajax.php',
					data: 
						'lang=' + LANG + '&' +
						'switch=index_get_locations&' +
						'country_id=' + $('#ddlMapCountry').val() + '&' +
						'region_id=' + $('#ddlMapRegion').val() + '&' +
						'city_id=' + $('#ddlMapCity').val(),
					dataType: 
						'html',
					success: function (responseText, responseCode, xhr) {
						map.clearMarkers();
						// Get locations
						map_markers = eval('[' + responseText + ']');
						setMarkers(map_markers);
					},
					error: function (xhr, responseCode) {
						alert('error');
					}
				});

				//setMarkers(map, map_markers);
			} 
			else {
				//
				alert('По вашему запросу ничего не найдено. Пожалуйста, уточните адрес.');
			}
		});
	}
	else {
		//
		alert('Error');
	}
}

//
function loadRegions(country_id)
{
	destination.push('map_regions');
	script_name = SITE_ROOT + "ajax.php?lang=" + LANG;
	ajax_req = 'country_id=' + country_id + '&switch=index_regions';
	cache.push(ajax_req);
	getAjaxRequest();
}

//
function loadCities()
{
	var region_id = $('#ddlMapRegion').val();
	destination.push('map_cities');
	script_name = SITE_ROOT + "ajax.php?lang=" + LANG;
	ajax_req = 'region_id=' + region_id + '&switch=index_cities';
	cache.push(ajax_req);
	getAjaxRequest();
}

//
function setMarkers(locations) {
	var image = new google.maps.MarkerImage(
		TPL_PATH + 'images/map_pointer.png',
		new google.maps.Size(20, 22),
		new google.maps.Point(0, 0),
		new google.maps.Point(0, 22)
	);
	var shape = {
		coord: [1, 1, 1, 20, 18, 20, 18, 1],
		type: 'poly'
	};
	for (var i = 0; i < locations.length; i++) {
		var place = locations[i];
		var myLatLng = new google.maps.LatLng(place[1], place[2]);
		var marker1 = new google.maps.Marker({
			position: myLatLng,
			map: map,
			//shadow: shadow,
			icon: image,
			shape: shape,
			title: place[0],
			zIndex: place[3]
		});
		google.maps.event.addListener(marker1, 'click', function () {
			var marker = this;
			var latLng = marker.getPosition();
			var currPlace;
			for (var j = 0; j < locations.length; j++)
			{
				currPlace = locations[j];
				if (currPlace[3] == marker.zIndex) {
					break;
				}
			}
			
			/*
				0.  branch_name
				1.  map_x
				2.  map_y
				3.  n
				4.  company_name
				5.  address
				6.  branch_url
				7.  company_url
				8.  logo
				9.  phone
				10. email
			 */
			infowindow.setContent(
				'<h2 style="margin-right:20px; color:#A91F2D;">' + currPlace[4] + '<br /><span style="color:#044c91;">' + currPlace[0] + '</span></h2>' +
				'<hr />' +
				'<div style="float:left;">' +
				'	<a href="' + SITE_ROOT + LANG + '/companies/' + currPlace[7] + '"><img src="' + SITE_ROOT +  'images/companies/logo/' + currPlace[8] + '" alt="" /></a>' +
				'</div>' + 
				'<div style="float:left; width:400px; margin-left:10px; line-height:22px;">' +
				'	<b>Адрес:</b> ' + currPlace[5] + '<br />' + 
				'	<b>Телефон:</b> ' + currPlace[9] + '<br />' + 
				'	<b>E-mail:</b> <a href="mailto:' + currPlace[10] + '" style="color:#5E5E5E;">' + currPlace[10] + '</a><br /><br />' +
				'	<a href="' + SITE_ROOT + LANG + '/companies/' + currPlace[7] + '">Дополнительная информация...</a>' + 
				'</div>' +
				'<div class="spacer"></div>'
			);
			//infowindow.setContent('<h3>Marker position is:</h3>' + latLng.lat() + ', ' + latLng.lng() + '<br />' + marker.title);
			infowindow.open(map, marker);
		});
	}
}